$(function() {
	const userData = JSON.parse(localStorage.getItem('userData'));

	//加载头像
	// $('.avatar').attr('src',`${baseURL}`+userData.avatar)

	//加载昵称
	$('.name').text(userData.nickName)

	let ioImg = '';

	$('#feature').on('change', function() {
		// 将 文件流 转换成 image/base64
		const reader = new FileReader();
		reader.readAsDataURL(this.files[0])
		reader.onload = function() {
			// 展示 图片
			$('.thumbnail').attr('src', reader.result)
			$('.thumbnail').css('display', 'block')

			ioImg = reader.result;
		}
	})

	$('.btn').click(function() {
		const title = $('#title').val().trim();
		const content = $('#content').val().trim();
		const feature = $('#feature').val().trim();
		let category = null;
		const created = $('#created').val();
		let status = null;

		$('#category option:selected').each(function(index, el) {
			category = $(el).text();
		})

		$('#status option:selected').each(function(index, el) {
			status = $(el).attr('value');
		})
		
		console.log('---------------  publish article ------------------');
		console.log({
				title: title,
				state: status,
				content: content,
				category: category,
				thumbnail: feature,
				createAt: moment().format('YYYY-MM-DD')
			})

		// 发布文章
		$.ajax(baseURL + '/posts', {
			method: 'post',
			data: {
				title: title,
				state: status,
				content: content,
				category: category,
				thumbnail: feature,
				createAt: moment().format('YYYY-MM-DD')
			},
			success: function(res) {
				alert('文章发布成功!', res);
			},
			error: function(err) {
				console.log(err);
				$('.alert').css('display', 'block');
				$('.alert').html('<strong>错误！</strong> 文章发布失败！')
			}
		})
	})
})
